package com.hermit.system.controller.admin;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.hermit.server.constants.Constants;
import com.hermit.server.domain.UserInfo;
import com.hermit.server.dto.LoginUserDto;
import com.hermit.server.dto.UserInfoDto;
import com.hermit.server.dto.PageDto;
import com.hermit.server.dto.ResponseDto;
import com.hermit.server.exception.ValidatorException;
import com.hermit.server.service.UserInfoService;
import com.hermit.server.util.UUidUtil;
import com.hermit.server.util.ValidatorUtil;
import org.apache.ibatis.annotations.Delete;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/admin/userInfo")
public class UserInfoController {

    private static final Logger LOG = LoggerFactory.getLogger(UserInfoController.class);
    public static final String BUSINESS_NAME = "用户信息";
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private RedisTemplate redisTemplate;

    @PostMapping("/list")
   public ResponseDto list(@RequestBody PageDto pageDto){
        LOG.info("pageDto: {}",pageDto);
        ResponseDto responseDto = new ResponseDto();
        userInfoService.list(pageDto);
        responseDto.setContent(pageDto);
        return responseDto;
    }

    @PostMapping("/save")
   public ResponseDto save(@RequestBody UserInfoDto userInfoDto){
        //二次password加密
        userInfoDto.setPassword(DigestUtils.md5DigestAsHex(userInfoDto.getPassword().getBytes()));
//        LOG.info("userInfoDto: {}",userInfoDto);
        /**保存校验*/
        ValidatorUtil.required(userInfoDto.getUsername(),"登录名");
        ValidatorUtil.length(userInfoDto.getUsername(),"登录名",1,50);
        ValidatorUtil.length(userInfoDto.getName(),"昵称",1,50);
        ValidatorUtil.required(userInfoDto.getPassword(),"密码");

        ResponseDto responseDto = new ResponseDto();
        userInfoService.save(userInfoDto);
        responseDto.setContent(userInfoDto);
        return responseDto;
    }

    @DeleteMapping("/delete/{id}")
   public ResponseDto delete(@PathVariable String id){
        LOG.info("id: {}",id);
        ResponseDto responseDto = new ResponseDto();
        userInfoService.delete(id);
        return responseDto;
    }

    @PostMapping("/save-password")
    public ResponseDto savePassword(@RequestBody UserInfoDto userInfoDto){
        //二次password加密
        userInfoDto.setPassword(DigestUtils.md5DigestAsHex(userInfoDto.getPassword().getBytes()));

        ResponseDto responseDto = new ResponseDto();
        userInfoService.savePassword(userInfoDto);
        responseDto.setContent(userInfoDto);
        return responseDto;
    }

    /**登陆*/
    @PostMapping("/login")
    public ResponseDto login(@RequestBody UserInfoDto userInfoDto, HttpServletRequest request){
        //加密
        userInfoDto.setPassword(DigestUtils.md5DigestAsHex(userInfoDto.getPassword().getBytes()));
        ResponseDto responseDto = new ResponseDto();

        //根据验证码token去获取缓存中的验证码，比较缓存验证码和用户验证码
//        String imageCode = (String) request.getSession().getAttribute(userInfoDto.getImageCodeToken());
        String imageCode = (String) redisTemplate.opsForValue().get(userInfoDto.getImageCodeToken());
        LOG.info("从redis中获取的验证码：{}" ,imageCode);
        if(StringUtils.isEmpty(imageCode)){
            responseDto.setSuccess(false);
            responseDto.setMessage("验证码已过期");
            LOG.info("用户登陆失败,验证码已过期");
            return responseDto;
        }
        if(!imageCode.toLowerCase().equals(userInfoDto.getImageCode().toLowerCase())){
            responseDto.setSuccess(false);
            responseDto.setMessage("验证码不正确");
            LOG.info("用户登陆失败,验证码不正确");
            return responseDto;
        }else{
//            request.getSession().removeAttribute(userInfoDto.getImageCodeToken());
            //验证通过后移验证码
            redisTemplate.delete(userInfoDto.getImageCodeToken());
        }

        LoginUserDto loginUserDto = userInfoService.login(userInfoDto);
//        request.getSession().setAttribute(Constants.LOGIN_USER,loginUserDto);
        String token = UUidUtil.getShortUuid();
        loginUserDto.setToken(token);
        redisTemplate.opsForValue().set(token, JSON.toJSONString(loginUserDto),3600, TimeUnit.SECONDS);
        responseDto.setContent(loginUserDto);
        return responseDto;
    }
    /**退出登陆*/
    @GetMapping("/logout/{token}")
    public ResponseDto logout(@PathVariable String token){
//        request.getSession().setAttribute("loginUser",null);
        ResponseDto responseDto = new ResponseDto();
//        request.getSession().removeAttribute(Constants.LOGIN_USER);
        redisTemplate.delete(token);
        LOG.info("从redis中删除:{}",token);
        return responseDto;
    }

}